<template>
  <el-form ref="form" :model="data" :rules="rules" label-width="100px" v-loading="loading">
    <el-form-item label="所属项目" prop="project_id">
      <el-select 
        v-model="data.project_id" 
        placeholder="请选择所属项目" 
        clearable 
        @change="select_project" 
        class="filter-item"
      >
        <el-option 
          v-for="(project,index) in project_list" 
          :key="index" 
          :label="project.title" 
          :value="project.id"
        ></el-option>
      </el-select>
    </el-form-item>
    
    <el-form-item label="所属建筑" prop="building_id">
      <el-select 
        v-model="data.building_id" 
        placeholder="请选择所属建筑" 
        clearable 
        class="filter-item"
      >
        <el-option 
          v-for="(building,index) in building_list" 
          :key="index" 
          :label="building.title" 
          :value="building.id"
        ></el-option>
      </el-select>
    </el-form-item>
    
    <el-form-item label="楼层名称" prop="title">
      <el-input v-model.trim="data.title" placeholder="请填写楼层名称" />
    </el-form-item>

    <el-dialog :visible.sync="dialogVisible" width="30%" append-to-body>
      <img width="100%" :src="previewUrl" alt="">
    </el-dialog>  
    
    <el-form-item>
      <el-button type="primary" :disabled="$store.state.settings.ajaxButton" @click="submit">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { detail, edit } from '@/api/projectfloor'
import { getToken } from '@/utils/auth'
import { commonApi } from '@/api/common' // 公共接口

export default {
  name: 'projectfloorEdit',
  components: { },
  props: {
    item: {
      type: Object,
      default: () => {
        return {}
      }
    },
    project_list: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: true,
      dialogVisible: false,
      previewUrl: '',
      building_list: [], // 建筑列表
      headerObj: {
        'Authorization': 'Bearer ' + getToken()
      },
      rules: {
        project_id: [ 
          { required: true, message: "请选择所属项目", trigger: "change" }
        ],
        building_id: [ 
          { required: true, message: "请选择所属建筑", trigger: "change" }
        ],
        title: [ 
          { required: true, message: "请输入楼层名称", trigger: "blur" }
        ]
      },
      data: {
        id: '',
        project_id: '',
        building_id: '',
        title: ''
      }
    }
  },
  created() {
    const id = this.item.id
    this.id = id
    this.fetchData(id)
  },
  watch: {
    item: {
      handler(val, oldVal) {
        if (this.item.dialogVisible === true) {
          this.id = val.id
          this.fetchData(val.id)
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取详情数据
    fetchData(id) {
      detail(id).then(response => {
        this.data = response.data
        // 如果有项目ID，则获取对应的建筑列表
        if (this.data.project_id) {
          this.select_project(this.data.project_id, true)
        } else {
          this.loading = false
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },

    // 选择项目
    select_project(value, isInit = false) {
      if (!value) {
        this.building_list = []
        this.data.building_id = '' // 清空建筑选择
        if (!isInit) {
          this.loading = false
        }
        return
      }
      
      commonApi.get_building({ project_id: value }).then(response => {
        this.building_list = response.data
        
        // 如果不是初始化，清空建筑选择
        if (!isInit) {
          this.data.building_id = ''
        } else {
          // 初始化时，检查建筑ID是否在返回的列表中
          const buildingExists = this.building_list.some(building => building.id === this.data.building_id)
          if (!buildingExists) {
            this.data.building_id = '' // 如果建筑不存在于列表中，清空选择
          }
        }
        
        this.loading = false
      }).catch(error => {
        console.error('获取建筑列表失败:', error)
        this.building_list = []
        this.loading = false
      })
    },

    submit() {
      const thiz = this
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
        
        this.$store.commit('settings/SET_AJAX_BUTTON', true)
        
        edit({
          id: this.data.id,
          project_id: this.data.project_id,
          building_id: this.data.building_id,
          title: this.data.title
        }).then(response => {
          this.$message({
            message: '编辑成功',
            type: 'success',
            duration: 1500,
            onClose() {
              thiz.$store.commit('settings/SET_AJAX_BUTTON', false)
              if (thiz.$refs.form !== undefined) {
                thiz.$refs.form.resetFields()
              }
              thiz.item.dialogVisible = false
              // 可选：触发父组件刷新数据
              thiz.$emit('success')
            }
          })
        }).catch(error => {
          this.$store.commit('settings/SET_AJAX_BUTTON', false)
          console.error('编辑失败:', error)
        })
      })
    }
  }
}
</script>